<#
调用示例:
.\initEnv-V2.ps1                            # 交互式安装模式
.\initEnv-V2.ps1 -Test                      # 测试模式（详细日志）
.\initEnv-V2.ps1 -All                       # 自动安装所有软件
.\initEnv-V2.ps1 -DiySoftware "git"            # 安装单个软件
.\initEnv-V2.ps1 -DiySoftware "git,ffmpeg,vim" # 安装多个软件
.\initEnv-V2.ps1 -DiySoftware "python" -Test   # 组合使用测试模式



#>

param(
    [Parameter(Mandatory=$false)]
    [switch]$Test,  # 测试模式（详细日志）

    [Parameter(Mandatory=$false)]
    [string]$DiySoftware=$null,  # 指定要安装的软件（多个用逗号分隔）

    [Parameter(Mandatory=$false)]
    [switch]$All,   # 自动安装所有软件
    
    [Parameter(Mandatory=$false)]
    [string]$OutputSavePath = "${env:USERPROFILE}\Downloads\WinSoftwares"  # 输出保存地址
)

# 操作系统版本检测
$OsVersion = 0
$os = Get-CimInstance -ClassName Win32_OperatingSystem -ErrorAction SilentlyContinue
if ($os) {
    $version = [version]$os.Version
    if ($version.Major -eq 6) {
        switch ($version.Minor) {
            1 { $OsVersion = 7 }   # Windows 7
            2 { $OsVersion = 8 }   # Windows 8
            3 { $OsVersion = 8.1 } # Windows 8.1
            default { $OsVersion = 0 }
        }
    } 
    elseif ($version.Major -eq 10) {
        # $OsVersion = ($version.Build -ge 22000) ? 11 : 10  # Win11 ≥ 22000
        # $OsVersion = ($version.Build -ge 22000) ? 11 : 10  # Win11 ≥ 22000
        if ($version.Build -ge 22000) {
            $OsVersion = 11
        } else {
            $OsVersion = 10
        }
    }
}

# 检查命令是否存在
function which ($command) {
    Get-Command -Name $command -ErrorAction SilentlyContinue |
        Select-Object -ExpandProperty Path -ErrorAction SilentlyContinue
}

# 增强日志函数
function XWrite-Host ($FLAG, $String) {
    $NowDateTime = Get-Date -f "HH:mm:ss"
    $color = switch ($FLAG.ToUpper()) {
        "INFO"    { "White" }
        "WARNING" { "Yellow" }
        "DEBUG"   { "Blue" }
        "ERROR"   { "Red" }
        default   { "Green" }
    }
    
    if ($Test -or $FLAG -in @("ERROR", "INFO")) {
        Write-Host "[$FLAG][$NowDateTime] $String" -ForegroundColor $color
    }
}

# 环境变量管理函数
function Add-EnvVars($AddEnvName, $AddEnvVal, $AddEnvClass) {
    $OrgPathParts = [System.Environment]::GetEnvironmentVariable($AddEnvName, $AddEnvClass) -split ";"
    if (-not ($OrgPathParts -contains $AddEnvVal)) {
        $NewPath = ($OrgPathParts + $AddEnvVal) -join ";"
        [System.Environment]::SetEnvironmentVariable($AddEnvName, $NewPath, $AddEnvClass)
        XWrite-Host "DEBUG" "Added $AddEnvVal to $AddEnvName"
    }
}

function Check-And-Add-UserEnvVars($TargetEnvPath) {
    if (Test-Path -Path $TargetEnvPath) {
        if (-not ($env:PATH.Contains($TargetEnvPath))) {
            Add-EnvVars "PATH" $TargetEnvPath "User"
            XWrite-Host "INFO" "Added to PATH: $TargetEnvPath"
        }
    } else {
        XWrite-Host "WARNING" "Path not found: $TargetEnvPath"
    }
}

# 下载函数
function Invoke-Download {
    param (
        [string]$uri,
        [string]$outputPath,
        [int]$sleeptimer = 30,
        [int]$maxTries = 3,
        [int]$tries = 0
    )
    
    if (Test-Path $outputPath) {
        XWrite-Host "INFO" "File exists: $outputPath"
        return
    }
    
    try {
        XWrite-Host "INFO" "Downloading: $uri ===> $outputPath"
        # 修复TLS协议问题
        [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor [System.Net.SecurityProtocolType]::Tls12
        Invoke-WebRequest -Uri $uri -OutFile $outputPath -UserAgent "Mozilla/5.0"  -UseBasicParsing -ErrorAction Stop
    }
    catch [System.Net.WebException] {
        $tries++
        if ($tries -lt $maxTries) {
            XWrite-Host "WARNING" "Retry $tries`/$maxTries`: $uri"
            Start-Sleep -Seconds $sleeptimer
            Invoke-Download -uri $uri -outputPath $outputPath -tries $tries
        } else {
            XWrite-Host "ERROR" "Failed after $maxTries attempts: $uri"
        }
    }
}

# 函数 
Function Download-Url-File($downloadUrl,$DownSaveDir=$OutputSavePath) {
    XWrite-Host "Debug" "This is Download-Url-File(). "; # 打印信息;
    # 解析 URL 并获取最后一段路径
    $resStr = "^$githubProxyUrl"
    $downloadUrlT = $downloadUrl -replace $resStr, '' # 去掉代理避免后面截取出错
    XWrite-Host "Debug" "downloadUrlT = $downloadUrlT"
    $uri = [System.Uri]$downloadUrlT
    $lastSegment = $uri.Segments[-1]
    # $lastSegment = $downloadUrl.split("/")[-1];
    # $segments = $downloadUrl -split '/' | Where-Object { $_ }
    # $lastSegment = $downloadUrl -split '/' | Where-Object { $_ } | Select-Object -Last 1 # # 更健壮的文件名提取方式
    XWrite-Host "Debug" "lastSegment = $lastSegment"
    # 智能替换文件名逻辑
    if ($lastSegment -match '^(main|master)\.zip$') { 
        # $saveFileNameT =  $uri.Segments[5] | ForEach-Object { $_.TrimEnd('/') } # 提取路径段并去除末尾斜杠
        $saveFileNameT =  $uri.Segments[2] | ForEach-Object { $_.TrimEnd('/') } # 取域名后第2个分段路径段并去除末尾斜杠
        $saveFileName =  "$saveFileNameT.zip"
        XWrite-Host "Debug" "saveFileNameT = $saveFileNameT"
        XWrite-Host "Debug" "saveFileName = $saveFileName"
    } else {
        $saveFileName = $lastSegment
    }
    $outputPath = "$DownSaveDir/$saveFileName";
    XWrite-Host "Debug" "The [ $downloadUrl ] file is being downloaded now. "; # 打印信息
    Invoke-Download $downloadUrl $outputPath;
    XWrite-Host "Debug" "The [ $downloadUrl ] file is downloaded and stored in [$outputPath]."; # 打印信息
}

# 软件安装函数（保持原有实现，此处省略）

# 静默安装
function installSoftware($softwarePath){
    # # 检查管理员权限
    # if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    #     Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs
    #     exit
    # }
    # 静默安装
    $logFile = "$softwarePath.log"
    try {
        # Write-Host "正在静默安装 $softwarePath..."
        XWrite-Host "INFO" "Installing silently  $softwarePath..."
        $installArgs = @(
            '/VERYSILENT',
            '/SUPPRESSMSGBOXES',
            '/NORESTART',
            '/SP-',
            "/LOG=$logFile"
        )
        Start-Process -FilePath $softwarePath -ArgumentList $installArgs -Wait -NoNewWindow
        # Write-Host "安装完成！"
        XWrite-Host "INFO" "Installation complete!"
    } catch {
        # Write-Host "安装失败: $_"
        XWrite-Host "INFO" "Installation failed: $_"
        exit 1
    }
    # 验证
}

# 初始化检查函数0: 下载后就是执行文件，移动到目录文件即可
function initMain0($softwareName,$EnvPath,$softwareDownloadUrl){
    XWrite-Host "Debug" "initMain0()"
    XWrite-Host "Debug" "softwareName = $softwareName"
    XWrite-Host "Debug" "softwareDownloadUrl = $softwareDownloadUrl"
    # 检查是否有（ 使用-not运算符判断）
    if ( -not $(which "$softwareName") ) {  # 不存在，则下载解压，添加环境变量
        $Url = $softwareDownloadUrl
        # 解析 URL 并获取最后一段路径
        $downloadUrl = [System.Uri]$Url
        $lastSegment = $downloadUrl.Segments[-1]
        $DownSaveDir = "${env:USERPROFILE}\Downloads\WinSoftwares" # 下载存放位置变量
        # 创建目标目录（如果不存在）
        if (-not (Test-Path -Path $DownSaveDir)) {
            New-Item -Path $DownSaveDir -ItemType Directory -Force | Out-Null
            XWrite-Host "INFO" "A directory has been created: $DownSaveDir" -ForegroundColor Cyan # 已创建目录
        }
        if (-not (Test-Path -Path $EnvPath)) {
            New-Item -Path $EnvPath -ItemType Directory -Force | Out-Null
            XWrite-Host "INFO" "A directory has been created: $EnvPath" -ForegroundColor Cyan # 已创建目录
        }
        # 下载
        Download-Url-File $Url $DownSaveDir
        $DownloadPath = "$DownSaveDir\$lastSegment" # 下载存放位置变量
        XWrite-Host "Debug" "DownloadPath = $DownloadPath"
        # 移动
        $cmd_string="Move-Item -Path $DownloadPath -Destination $EnvPath" # 拷贝文件到对应目录下
        XWrite-Host "INFO" "cmd_string = $cmd_string"
        Invoke-Expression $cmd_string # 执行命令
    } else {
        # 存在
        XWrite-Host "Debug" "$softwareName is exist."
    }

}

# 初始化检查函数0-1: 下载后就是执行文件,但名字不一样，移动到目录文件并重命名
function initMain0-1($softwareName,$EnvPath,$softwareDownloadUrl){
    XWrite-Host "Debug" "initMain0-1()"
    XWrite-Host "Debug" "softwareName = $softwareName"
    XWrite-Host "Debug" "softwareDownloadUrl = $softwareDownloadUrl"
    # 检查是否有（ 使用-not运算符判断）
    if ( -not $(which "$softwareName") ) {  # 不存在，则下载解压，添加环境变量
        $Url = $softwareDownloadUrl
        # 解析 URL 并获取最后一段路径
        $downloadUrl = [System.Uri]$Url
        $lastSegment = $downloadUrl.Segments[-1]
        $DownSaveDir = "${env:USERPROFILE}\Downloads\WinSoftwares" # 下载存放位置变量
        # 创建目标目录（如果不存在）
        if (-not (Test-Path -Path $DownSaveDir)) {
            New-Item -Path $DownSaveDir -ItemType Directory -Force | Out-Null
            XWrite-Host "INFO" "A directory has been created: $DownSaveDir" -ForegroundColor Cyan # 已创建目录
        }
        if (-not (Test-Path -Path $EnvPath)) {
            New-Item -Path $EnvPath -ItemType Directory -Force | Out-Null
            XWrite-Host "INFO" "A directory has been created: $EnvPath" -ForegroundColor Cyan # 已创建目录
        }
        # 下载
        Download-Url-File $Url $DownSaveDir
        $DownloadPath = "$DownSaveDir\$lastSegment" # 下载存放位置变量
        XWrite-Host "Debug" "DownloadPath = $DownloadPath"

        # 移动
        $cmd_string="Move-Item -Path $DownloadPath -Destination $EnvPath" # 拷贝文件到对应目录下
        XWrite-Host "INFO" "cmd_string = $cmd_string"
        Invoke-Expression $cmd_string # 执行命令

        # 重命名
        $cmd_string="Rename-Item -Path $EnvPath\$lastSegment -NewName $EnvPath\$softwareName "
        XWrite-Host "INFO" "cmd_string = $cmd_string"
        Invoke-Expression $cmd_string # 执行命令

    } else {
        # 存在
        XWrite-Host "Debug" "$softwareName is exist."
    }

}

# 初始化检查函数1: 下载后解压出来就是执行文件（没有文件夹），直接解压到目的目录即可
function initMain1($softwareName,$ExpandOutPath,$softwareDownloadUrl){
    XWrite-Host "Debug" "initMain1()"
    XWrite-Host "Debug" "softwareName = $softwareName"
    XWrite-Host "Debug" "softwareDownloadUrl = $softwareDownloadUrl"
    # 检查是否有 （使用-not运算符判断）
    if ( -not $(which "$softwareName") ) { # 不存在，则下载解压，添加环境变量
        $Url = $softwareDownloadUrl
        # 解析 URL 并获取最后一段路径
        $downloadUrl = [System.Uri]$Url
        $lastSegment = $downloadUrl.Segments[-1]
        # 
        $DownSaveDir = "${env:USERPROFILE}\Downloads\WinSoftwares" # 下载存放位置变量
        # 创建目标目录（如果不存在）
        if (-not (Test-Path -Path $DownSaveDir)) {
            New-Item -Path $DownSaveDir -ItemType Directory -Force | Out-Null
            XWrite-Host "INFO" "A directory has been created: $DownSaveDir" -ForegroundColor Cyan # 已创建目录
        }
        if (-not (Test-Path -Path $ExpandOutPath)) {
            New-Item -Path $ExpandOutPath -ItemType Directory -Force | Out-Null
            XWrite-Host "INFO" "A directory has been created: $ExpandOutPath" -ForegroundColor Cyan # 已创建目录
        }
        # 下载
        Download-Url-File $Url $DownSaveDir
        $DownloadPath = "$DownSaveDir\$lastSegment" # 下载存放位置变量
        XWrite-Host "Debug" "DownloadPath = $DownloadPath"
        # 解压到指定文件夹或，解压后拷贝到指定位置
       if ($lastSegment -match '(tar)\.gz$') { # 是tar.gz格式
            XWrite-Host "Debug" "The file  is tar.gz"# 是tar.gz格式
            if (which "tar") {
                # & tar -zxvf "$DownloadPath"   # 解压 .tar.gz 文件
                $lastSegmentT = $lastSegment  -replace '\.tar\.gz$', '' # 正则替换去除
                mkdir -p "$DownSaveDir\$lastSegmentT"
                & tar -zxvf "$DownloadPath" -C "$DownSaveDir\$lastSegmentT"  # 解压 .tar.gz 文件
                # exit 1
                # exit 1
            } elseif (which "7z") {
                # Windows 7 默认的 PowerShell 5.1 基于 .NET Framework 4.x，不支持 TarFile 类（需要 .NET 7+ 或 PowerShell 7+）。
                # 若需原生支持，需升级到 PowerShell 7，但 Windows 7 需安装 Extended Security Update。
                # 使用7z解压
                # Install-Module -Name 7Zip4PowerShell -Scope CurrentUser
                $lastSegmentT = $lastSegment  -replace '\.tar\.gz$', '' # 正则替换去除
                $7zipPath = "7z"
                $tarGzFile = "$DownloadPath"
                XWrite-Host "Debug" "tarGzFile = $tarGzFile"
                $extractDir = "$DownSaveDir\$lastSegmentT"
                XWrite-Host "Debug" "extractDir = $extractDir"
                # 解压 .tar.gz -> 先解压为 .tar，再解包
                & $7zipPath x $tarGzFile -o"$extractDir" -y  # 解压 .tar.gz 到目标目录
                & $7zipPath x "$extractDir\*.tar" -o"$extractDir" -y  # 解压 .tar 文件

                # # 移动
                # $cmd_string="Move-Item -Path $extractDir\$softwareName`.exe -Destination $ExpandOutPath" # 拷贝文件到对应目录下
                # XWrite-Host "INFO" "cmd_string = $cmd_string"
                # Invoke-Expression $cmd_string # 执行命令

                # # 删除解压过程文件
                # if ($lastSegment -match '(tar)\.gz$') { # 是tar.gz格式
                #     $cmd_string= "Remove-Item -Recurse -Force -Path $extractDir" 
                #     XWrite-Host "INFO" "cmd_string = $cmd_string"
                #     Invoke-Expression $cmd_string # 执行命令
                # }
            } else {
                XWrite-Host "INFO" "The 7-Zip 、tar is not installed."
            }
        } else {
            $cmd_string="Expand-Archive  -Force -LiteralPath $DownloadPath -DestinationPath $ExpandOutPath" # 在下载保存目录解
            XWrite-Host "INFO" "cmd_string = $cmd_string"
            Invoke-Expression $cmd_string # 执行命令
        }

    } else {
        # 存在
        XWrite-Host "Debug"  "$softwareName is exist."
    }

}
# 初始化检查函数1-1: 下载后解压出来就是执行文件，找到执行文件拷贝到指定目录即可 并重命令
function initMain1-1($softwareName,$ExpandOutPath,$softwareDownloadUrl,$RenameFilepath){
    XWrite-Host "Debug" "initMain1-1()"
    XWrite-Host "Debug" "softwareName = $softwareName"
    XWrite-Host "Debug" "softwareDownloadUrl = $softwareDownloadUrl"
    # 检查是否有
    # 使用-not运算符判断
    if ( -not $(which "$softwareName") ) { # 不存在，则下载解压，添加环境变量
        $Url = $softwareDownloadUrl
        # 解析 URL 并获取最后一段路径
        $downloadUrl = [System.Uri]$Url
        $lastSegment = $downloadUrl.Segments[-1]
        # 
        $DownSaveDir = "${env:USERPROFILE}\Downloads\WinSoftwares" # 下载存放位置变量
        # 创建目标目录（如果不存在）
        if (-not (Test-Path -Path $DownSaveDir)) {
            New-Item -Path $DownSaveDir -ItemType Directory -Force | Out-Null
            XWrite-Host "INFO" "A directory has been created: $DownSaveDir" -ForegroundColor Cyan # 已创建目录
        }
        if (-not (Test-Path -Path $ExpandOutPath)) {
            New-Item -Path $ExpandOutPath -ItemType Directory -Force | Out-Null
            XWrite-Host "INFO" "A directory has been created: $ExpandOutPath" -ForegroundColor Cyan # 已创建目录
        }
        # 下载
        Download-Url-File $Url $DownSaveDir
        $DownloadPath = "$DownSaveDir\$lastSegment" # 下载存放位置变量
        XWrite-Host "Debug" "DownloadPath = $DownloadPath"

        # 解压
        $cmd_string="Expand-Archive -Force -LiteralPath $DownloadPath -DestinationPath $DownSaveDir" # 在下载保存目录解
        XWrite-Host "INFO" "cmd_string = $cmd_string"
        Invoke-Expression $cmd_string # 执行命令
        # 移动
        $cmd_string="Move-Item -Path $DownSaveDir\$RenameFilepath    -Destination $ExpandOutPath\$softwareName" # 拷贝文件到对应目录下
        XWrite-Host "INFO" "cmd_string = $cmd_string"
        # XWrite-Host "Warning" "cmd_string = $cmd_string"
        Invoke-Expression $cmd_string # 执行命令

        # 检查是否有环境变量加入，没有则加入

        # 删除解压遗留
        if(Test-Path "$DownSaveDir\$RenameFilepath") {
            # $cmd_string= "Remove-Item -Recurse -Force -Path $DownSaveDir\$MoveSubPath\* "
            # XWrite-Host "INFO" "cmd_string = $cmd_string"
            # Invoke-Expression $cmd_string # 执行命令
            $cmd_string= "Remove-Item -Recurse -Force -Path $DownSaveDir\$RenameFilepath" 
            XWrite-Host "INFO" "cmd_string = $cmd_string"
            Invoke-Expression $cmd_string # 执行命令
        }

    } else {
        # 存在
        XWrite-Host "Debug" "$softwareName is exist."
    }
}

# 初始化检查函数1-2: 下载后解压出来需要进入一两级目录，找到执行文件拷贝到指定目录即可 并重命令
function initMain1-2($softwareName,$ExpandOutPath,$softwareDownloadUrl,$ExpandTemSubPath,$RenameFilepath){
    XWrite-Host "Debug" "initMain1-2()"
    XWrite-Host "Debug" "softwareName = $softwareName"
    XWrite-Host "Debug" "softwareDownloadUrl = $softwareDownloadUrl"
    # 检查是否有
    # 使用-not运算符判断
    if ( -not $(which "$softwareName") ) { # 不存在，则下载解压，添加环境变量
        $Url = $softwareDownloadUrl
        # 解析 URL 并获取最后一段路径
        $downloadUrl = [System.Uri]$Url
        $lastSegment = $downloadUrl.Segments[-1]
        # 
        $DownSaveDir = "${env:USERPROFILE}\Downloads\WinSoftwares" # 下载存放位置变量
        # 创建目标目录（如果不存在）
        if (-not (Test-Path -Path $DownSaveDir)) {
            New-Item -Path $DownSaveDir -ItemType Directory -Force | Out-Null
            XWrite-Host "INFO" "A directory has been created: $DownSaveDir" -ForegroundColor Cyan # 已创建目录
        }
        if (-not (Test-Path -Path $ExpandOutPath)) {
            New-Item -Path $ExpandOutPath -ItemType Directory -Force | Out-Null
            XWrite-Host "INFO" "A directory has been created: $ExpandOutPath" -ForegroundColor Cyan # 已创建目录
        }
        # 下载
        Download-Url-File $Url $DownSaveDir
        $DownloadPath = "$DownSaveDir\$lastSegment" # 下载存放位置变量
        XWrite-Host "Debug" "DownloadPath = $DownloadPath"

        # 解压
        $cmd_string="Expand-Archive -Force -LiteralPath $DownloadPath -DestinationPath $DownSaveDir" # 在下载保存目录解
        XWrite-Host "INFO" "cmd_string = $cmd_string"
        Invoke-Expression $cmd_string # 执行命令
        # 移动
        $cmd_string="Move-Item -Path $DownSaveDir\$ExpandTemSubPath\$RenameFilepath    -Destination $ExpandOutPath\$softwareName" # 拷贝文件到对应目录下
        # XWrite-Host "INFO" "cmd_string = $cmd_string"
        XWrite-Host "Warning" "cmd_string = $cmd_string"
        # Invoke-Expression $cmd_string # 执行命令

        # 检查是否有环境变量加入，没有则加入

        # 删除解压遗留
        # if(Test-Path "$DownSaveDir\$ExpandTemSubPath") {
        #     # $cmd_string= "Remove-Item -Recurse -Force -Path $DownSaveDir\$MoveSubPath\* "
        #     # XWrite-Host "INFO" "cmd_string = $cmd_string"
        #     # Invoke-Expression $cmd_string # 执行命令
        #     $cmd_string= "Remove-Item -Recurse -Force -Path $DownSaveDir\$ExpandTemSubPath" 
        #     XWrite-Host "INFO" "cmd_string = $cmd_string"
        #     Invoke-Expression $cmd_string # 执行命令
        # }

    } else {
        # 存在
        XWrite-Host "Debug" "$softwareName is exist."
    }
}

# 初始化检查函数2: 下载后解压出来需要进入一两级目录，找到执行文件拷贝到指定目录即可
function initMain2($softwareName,$ExpandOutPath,$softwareDownloadUrl,$MoveSubPath){
    XWrite-Host "Debug" "initMain2()"
    XWrite-Host "Debug" "softwareName = $softwareName"
    XWrite-Host "Debug" "softwareDownloadUrl = $softwareDownloadUrl"
    # 检查是否有
    # 使用-not运算符判断
    if ( -not $(which "$softwareName") ) { # 不存在，则下载解压，添加环境变量
        $Url = $softwareDownloadUrl
        # 解析 URL 并获取最后一段路径
        $downloadUrl = [System.Uri]$Url
        $lastSegment = $downloadUrl.Segments[-1]
        # 
        $DownSaveDir = "${env:USERPROFILE}\Downloads\WinSoftwares" # 下载存放位置变量
        # 创建目标目录（如果不存在）
        if (-not (Test-Path -Path $DownSaveDir)) {
            New-Item -Path $DownSaveDir -ItemType Directory -Force | Out-Null
            XWrite-Host "INFO" "A directory has been created: $DownSaveDir" -ForegroundColor Cyan # 已创建目录
        }
        if (-not (Test-Path -Path $ExpandOutPath)) {
            New-Item -Path $ExpandOutPath -ItemType Directory -Force | Out-Null
            XWrite-Host "INFO" "A directory has been created: $ExpandOutPath" -ForegroundColor Cyan # 已创建目录
        }
        # 下载
        Download-Url-File $Url $DownSaveDir
        $DownloadPath = "$DownSaveDir\$lastSegment" # 下载存放位置变量
        XWrite-Host "Debug" "DownloadPath = $DownloadPath"

        # 解压
        $cmd_string="Expand-Archive -Force -LiteralPath $DownloadPath -DestinationPath $DownSaveDir" # 在下载保存目录解
        XWrite-Host "INFO" "cmd_string = $cmd_string"
        Invoke-Expression $cmd_string # 执行命令
        # 移动
        $cmd_string="Move-Item -Path $DownSaveDir\$MoveSubPath\* -Destination $ExpandOutPath" # 拷贝文件到对应目录下
        XWrite-Host "INFO" "cmd_string = $cmd_string"
        Invoke-Expression $cmd_string # 执行命令

        # 检查是否有环境变量加入，没有则加入

        # 删除解压遗留
        if(Test-Path "$DownSaveDir\$MoveSubPath") {
            # $cmd_string= "Remove-Item -Recurse -Force -Path $DownSaveDir\$MoveSubPath\* "
            # XWrite-Host "INFO" "cmd_string = $cmd_string"
            # Invoke-Expression $cmd_string # 执行命令
            $cmd_string= "Remove-Item -Recurse -Force -Path $DownSaveDir\$MoveSubPath" 
            XWrite-Host "INFO" "cmd_string = $cmd_string"
            Invoke-Expression $cmd_string # 执行命令
        }

    } else {
        # 存在
        XWrite-Host "Debug" "$softwareName is exist."
    }
}
# 初始化检查函数3: 下载后解压出来的文件不是单个可执行文件，拷贝到指定目录，并添加目录到环境变量中
function initMain3($softwareName,$EnvPath,$softwareDownloadUrl,$MoveSubPath){
    XWrite-Host "Debug" "initMain3()"
    XWrite-Host "Debug" "softwareName = $softwareName"
    XWrite-Host "Debug" "softwareDownloadUrl = $softwareDownloadUrl"
    # 检查是否有 （使用-not运算符判断）
    if ( -not $(which "$softwareName") ){ # 不存在，则下载解压，添加环境变量
        $Url = $softwareDownloadUrl
        # 解析 URL 并获取最后一段路径
        $downloadUrl = [System.Uri]$Url
        $lastSegment = $downloadUrl.Segments[-1]
        # 
        $DownSaveDir = "${env:USERPROFILE}\Downloads\WinSoftwares" # 下载存放位置变量
        # 创建目标目录（如果不存在）
        if (-not (Test-Path -Path $DownSaveDir)) {
            New-Item -Path $DownSaveDir -ItemType Directory -Force | Out-Null
            XWrite-Host "INFO" "A directory has been created: $DownSaveDir" -ForegroundColor Cyan # 已创建目录
        }
        if (-not (Test-Path -Path $EnvPath)) {
            New-Item -Path $EnvPath -ItemType Directory -Force | Out-Null
            XWrite-Host "INFO" "A directory has been created: $EnvPath" -ForegroundColor Cyan # 已创建目录
        }
        # 下载
        Download-Url-File $Url $DownSaveDir
        $DownloadPath = "$DownSaveDir\$lastSegment" # 下载存放位置变量
        XWrite-Host "Debug" "DownloadPath = $DownloadPath"
        # 解压
        # 解压到指定文件夹或，解压后拷贝到指定位置
       if ($lastSegment -match '(tar)\.gz$') { # 是tar.gz格式
            XWrite-Host "Debug" "The file  is tar.gz"# 是tar.gz格式
            if (which "tar") {
                # & tar -zxvf "$DownloadPath"   # 解压 .tar.gz 文件
                $lastSegmentT = $lastSegment  -replace '\.tar\.gz$', '' # 正则替换去除
                mkdir -p "$DownSaveDir\$lastSegmentT"
                & tar -zxvf "$DownloadPath" -C "$DownSaveDir\$lastSegmentT"  # 解压 .tar.gz 文件
                # exit 1
            } elseif (which "7z") {
                # Windows 7 默认的 PowerShell 5.1 基于 .NET Framework 4.x，不支持 TarFile 类（需要 .NET 7+ 或 PowerShell 7+）。
                # 若需原生支持，需升级到 PowerShell 7，但 Windows 7 需安装 Extended Security Update。
                # 使用7z解压
                # Install-Module -Name 7Zip4PowerShell -Scope CurrentUser
                $lastSegmentT = $lastSegment  -replace '\.tar\.gz$', '' # 正则替换去除
                $7zipPath = "7z"
                $tarGzFile = "$DownloadPath"
                XWrite-Host "Debug" "tarGzFile = $tarGzFile"
                $extractDir = "$DownSaveDir\$lastSegmentT"
                XWrite-Host "Debug" "extractDir = $extractDir"
                # 解压 .tar.gz -> 先解压为 .tar，再解包
                & $7zipPath x $tarGzFile -o"$extractDir" -y  # 解压 .tar.gz 到目标目录
                & $7zipPath x "$extractDir\*.tar" -o"$extractDir" -y  # 解压 .tar 文件

                # # 移动
                # $cmd_string="Move-Item -Path $extractDir\$softwareName`.exe -Destination $ExpandOutPath" # 拷贝文件到对应目录下
                # XWrite-Host "INFO" "cmd_string = $cmd_string"
                # Invoke-Expression $cmd_string # 执行命令

                # # 删除解压过程文件
                # if ($lastSegment -match '(tar)\.gz$') { # 是tar.gz格式
                #     $cmd_string= "Remove-Item -Recurse -Force -Path $extractDir" 
                #     XWrite-Host "INFO" "cmd_string = $cmd_string"
                #     Invoke-Expression $cmd_string # 执行命令
                # }
            } else {
                XWrite-Host "INFO" "The 7-Zip 、tar is not installed."
            }
        } else {
            $cmd_string="Expand-Archive  -Force -LiteralPath $DownloadPath -DestinationPath $DownSaveDir" # 在下载保存目录解
            XWrite-Host "INFO" "cmd_string = $cmd_string"
            Invoke-Expression $cmd_string # 执行命令
        }
        # 移动
        $cmd_string="Move-Item -Path $DownSaveDir\$MoveSubPath -Destination $EnvPath" # 拷贝文件到对应目录下
        XWrite-Host "INFO" "cmd_string = $cmd_string"
        Invoke-Expression $cmd_string # 执行命令

        # 删除下载文件
        if(Test-Path "$DownSaveDir\$MoveSubPath") {
            # $cmd_string= "Remove-Item -Recurse -Force -Path $DownSaveDir\$MoveSubPath\* "
            # XWrite-Host "INFO" "cmd_string = $cmd_string"
            # Invoke-Expression $cmd_string # 执行命令
            $cmd_string= "Remove-Item -Recurse -Force -Path $DownSaveDir\$MoveSubPath" 
            XWrite-Host "INFO" "cmd_string = $cmd_string"
            Invoke-Expression $cmd_string # 执行命令
        }
        # 添加环境变量
        $fullEnvPath = "$EnvPath\$MoveSubPath"
        XWrite-Host "INFO" "fullEnvPath = $fullEnvPath"
        if (Test-Path -Path $fullEnvPath) { # 存在则j
            Check-And-Add-USerEnvVars "$fullEnvPath"
        } else {
            XWrite-Host "Error"  "$fullEnvPath is not exist."
        }
    } else {
        # 存在
        XWrite-Host "Debug"  "$softwareName is exist."
    }

}

# 初始化检查函数3-1: 下载后解压出来的文件不是单个可执行文件（且解压没有外壳，需自自己指定个或建立个好方便后面移动），拷贝到指定目录，并添加目录到环境变量中
function initMain3-1($softwareName,$EnvPath,$softwareDownloadUrl,$MoveSubPath){
    XWrite-Host "Debug" "initMain3()"
    XWrite-Host "Debug" "softwareName = $softwareName"
    XWrite-Host "Debug" "softwareDownloadUrl = $softwareDownloadUrl"
    # 检查是否有 （使用-not运算符判断）
    if ( -not $(which "$softwareName") ){ # 不存在，则下载解压，添加环境变量
        $Url = $softwareDownloadUrl
        # 解析 URL 并获取最后一段路径
        $downloadUrl = [System.Uri]$Url
        $lastSegment = $downloadUrl.Segments[-1]
        # 
        $DownSaveDir = "${env:USERPROFILE}\Downloads\WinSoftwares" # 下载存放位置变量
        # 创建目标目录（如果不存在）
        if (-not (Test-Path -Path $DownSaveDir)) {
            New-Item -Path $DownSaveDir -ItemType Directory -Force | Out-Null
            XWrite-Host "INFO" "A directory has been created: $DownSaveDir" -ForegroundColor Cyan # 已创建目录
        }
        if (-not (Test-Path -Path $EnvPath)) {
            New-Item -Path $EnvPath -ItemType Directory -Force | Out-Null
            XWrite-Host "INFO" "A directory has been created: $EnvPath" -ForegroundColor Cyan # 已创建目录
        }
        # 下载
        Download-Url-File $Url $DownSaveDir
        $DownloadPath = "$DownSaveDir\$lastSegment" # 下载存放位置变量
        XWrite-Host "Debug" "DownloadPath = $DownloadPath"
        # 解压
        $cmd_string="Expand-Archive  -Force -LiteralPath $DownloadPath -DestinationPath $DownSaveDir\$MoveSubPath" # 在下载保存目录解
        XWrite-Host "INFO" "cmd_string = $cmd_string"
        Invoke-Expression $cmd_string # 执行命令
        # 移动
        $cmd_string="Move-Item -Path $DownSaveDir\$MoveSubPath -Destination $EnvPath" # 拷贝文件到对应目录下
        XWrite-Host "INFO" "cmd_string = $cmd_string"
        Invoke-Expression $cmd_string # 执行命令

        # 删除下载文件
        if(Test-Path "$DownSaveDir\$MoveSubPath") {
            # $cmd_string= "Remove-Item -Recurse -Force -Path $DownSaveDir\$MoveSubPath\* "
            # XWrite-Host "INFO" "cmd_string = $cmd_string"
            # Invoke-Expression $cmd_string # 执行命令
            $cmd_string= "Remove-Item -Recurse -Force -Path $DownSaveDir\$MoveSubPath" 
            XWrite-Host "INFO" "cmd_string = $cmd_string"
            Invoke-Expression $cmd_string # 执行命令
        }
        # 添加环境变量
        $fullEnvPath = "$EnvPath\$MoveSubPath"
        XWrite-Host "INFO" "fullEnvPath = $fullEnvPath"
        if (Test-Path -Path $fullEnvPath) { # 存在则j
            Check-And-Add-USerEnvVars "$fullEnvPath"
        } else {
            XWrite-Host "Error"  "$fullEnvPath is not exist."
        }
    } else {
        # 存在
        XWrite-Host "Debug"  "$softwareName is exist."
    }

}

# 初始化检查函数4: 下载后解压出来的文件不是单个可执行文件，拷贝到指定目录，并重命名，并添加目录到环境变量中
function initMain4($softwareName,$EnvPath,$softwareDownloadUrl,$MoveSubPath){
    XWrite-Host "Debug" "initMain4()"
    XWrite-Host "Debug" "softwareName = $softwareName"
    XWrite-Host "Debug" "softwareDownloadUrl = $softwareDownloadUrl"
    # 检查是否有 （使用-not运算符判断）
    if ( -not (Test-Path -Path "$EnvPath\$softwareName" )){ # 不存在，则下载解压，添加环境变量
        $Url = $softwareDownloadUrl
        # 解析 URL 并获取最后一段路径
        $resStr = "^$githubProxyUrl"
        $downloadUrlT = $Url -replace $resStr, '' # 去掉代理避免后面截取出错
        XWrite-Host "Debug" "downloadUrlT = $downloadUrlT"
        $downloadUrl = [System.Uri]$downloadUrlT
        $lastSegment = $downloadUrl.Segments[-1]
        # 智能替换文件名逻辑
        if ($lastSegment -match '^(main|master)\.zip$') {
            $saveFileNameT =  $downloadUrl.Segments[2] | ForEach-Object { $_.TrimEnd('/') } # 取域名后第2个分段路径段并去除末尾斜杠
            $lastSegment =  "$saveFileNameT.zip"
        } 
        XWrite-Host "Debug" "lastSegment = $lastSegment"
        $DownSaveDir = "${env:USERPROFILE}\Downloads\WinSoftwares" # 下载存放位置变量
        # 创建目标目录（如果不存在）
        if (-not (Test-Path -Path $DownSaveDir)) {
            New-Item -Path $DownSaveDir -ItemType Directory -Force | Out-Null
            XWrite-Host "INFO" "A directory has been created: $DownSaveDir" -ForegroundColor Cyan # 已创建目录
        }
        if (-not (Test-Path -Path $EnvPath)) {
            New-Item -Path $EnvPath -ItemType Directory -Force | Out-Null
            XWrite-Host "INFO" "A directory has been created: $EnvPath" -ForegroundColor Cyan # 已创建目录
        }
        # 下载
        Download-Url-File $softwareDownloadUrl $DownSaveDir
        $DownloadPath = "$DownSaveDir\$lastSegment" # 下载存放位置变量
        XWrite-Host "Debug" "DownloadPath = $DownloadPath"
        # 解压
        $cmd_string="Expand-Archive -Force -LiteralPath $DownloadPath -DestinationPath $DownSaveDir" # 在下载保存目录解
        XWrite-Host "INFO" "cmd_string = $cmd_string"
        Invoke-Expression $cmd_string # 执行命令

        # 重命名
        $cmd_string="Rename-Item -Path $DownSaveDir\$MoveSubPath -NewName $DownSaveDir\$softwareName "
        XWrite-Host "INFO" "cmd_string = $cmd_string"
        Invoke-Expression $cmd_string # 执行命令

        # 移动
        $cmd_string="Move-Item -Path $DownSaveDir\$softwareName -Destination $EnvPath" # 拷贝文件到对应目录下
        XWrite-Host "INFO" "cmd_string = $cmd_string"
        Invoke-Expression $cmd_string # 执行命令

        # 删除下载文件
        if(Test-Path "$DownSaveDir\$MoveSubPath") {
            # $cmd_string= "Remove-Item -Recurse -Force -Path $DownSaveDir\$MoveSubPath\* "
            # XWrite-Host "INFO" "cmd_string = $cmd_string"
            # Invoke-Expression $cmd_string # 执行命令
            $cmd_string= "Remove-Item -Recurse -Force -Path $DownSaveDir\$MoveSubPath" 
            XWrite-Host "INFO" "cmd_string = $cmd_string"
            Invoke-Expression $cmd_string # 执行命令
        }
        # 添加环境变量
        $fullEnvPath = "$EnvPath\$softwareName"
        XWrite-Host "INFO" "fullEnvPath = $fullEnvPath"
        if (Test-Path -Path $fullEnvPath) { # 存在则j
            Check-And-Add-USerEnvVars "$fullEnvPath"
        } else {
            XWrite-Host "Error"  "$fullEnvPath is not exist."
        }
    } else {
        # 存在
        XWrite-Host "Debug"  "$softwareName is exist."
    }

}

# 初始化检查函数5: 下载后解压出来的文件不是单个可执行文件，并且没有最外层文件，拷贝到指定目录，并添加目录到环境变量中
function initMain5($softwareName,$EnvPath,$softwareDownloadUrl,$MoveSubPath){
    XWrite-Host "Debug" "initMain5()"
    XWrite-Host "Debug" "softwareName = $softwareName"
    XWrite-Host "Debug" "softwareDownloadUrl = $softwareDownloadUrl"
    # 检查是否有 （使用-not运算符判断）
    if ( -not $(which "$softwareName") ){ # 不存在，则下载解压，添加环境变量
        $Url = $softwareDownloadUrl
        # 解析 URL 并获取最后一段路径
        $downloadUrl = [System.Uri]$Url
        $lastSegment = $downloadUrl.Segments[-1]
        # 
        $DownSaveDir = "${env:USERPROFILE}\Downloads\WinSoftwares" # 下载存放位置变量
        # 创建目标目录（如果不存在）
        if (-not (Test-Path -Path $DownSaveDir)) {
            New-Item -Path $DownSaveDir -ItemType Directory -Force | Out-Null
            XWrite-Host "INFO" "A directory has been created: $DownSaveDir" -ForegroundColor Cyan # 已创建目录
        }
        if (-not (Test-Path -Path $EnvPath)) {
            New-Item -Path $EnvPath -ItemType Directory -Force | Out-Null
            XWrite-Host "INFO" "A directory has been created: $EnvPath" -ForegroundColor Cyan # 已创建目录
        }
        # 下载
        Download-Url-File $Url $DownSaveDir
        $DownloadPath = "$DownSaveDir\$lastSegment" # 下载存放位置变量
        XWrite-Host "Debug" "DownloadPath = $DownloadPath"
        # 解压
        $cmd_string="Expand-Archive  -Force -LiteralPath $DownloadPath -DestinationPath $DownSaveDir\$MoveSubPath" # 在下载保存目录解
        XWrite-Host "INFO" "cmd_string = $cmd_string"
        Invoke-Expression $cmd_string # 执行命令
        # 移动
        $cmd_string="Move-Item -Path $DownSaveDir\$MoveSubPath -Destination $EnvPath" # 拷贝文件到对应目录下
        XWrite-Host "INFO" "cmd_string = $cmd_string"
        Invoke-Expression $cmd_string # 执行命令

        # 删除下载文件
        if(Test-Path "$DownSaveDir\$MoveSubPath") {
            # $cmd_string= "Remove-Item -Recurse -Force -Path $DownSaveDir\$MoveSubPath\* "
            # XWrite-Host "INFO" "cmd_string = $cmd_string"
            # Invoke-Expression $cmd_string # 执行命令
            $cmd_string= "Remove-Item -Recurse -Force -Path $DownSaveDir\$MoveSubPath" 
            XWrite-Host "INFO" "cmd_string = $cmd_string"
            Invoke-Expression $cmd_string # 执行命令
        }
        # 添加环境变量
        $fullEnvPath = "$EnvPath\$MoveSubPath"
        XWrite-Host "INFO" "fullEnvPath = $fullEnvPath"
        if (Test-Path -Path $fullEnvPath) { # 存在则
            Check-And-Add-USerEnvVars "$fullEnvPath"
        } else {
            XWrite-Host "Error"  "$fullEnvPath is not exist."
        }
    } else {
        # 存在
        XWrite-Host "Debug"  "$softwareName is exist."
    }

}

# 初始化检查函数5-1: 下载后解压出来的文件是多级单个可执行文件，并且没有最外层文件，拷贝到指定目录，并添加目录到环境变量中
function initMain5-1($softwareName,$EnvDir,$softwareDownloadUrl,$MoveSubPath,$EnvPath){
    XWrite-Host "Debug" "initMain5()"
    XWrite-Host "Debug" "softwareName = $softwareName"
    XWrite-Host "Debug" "softwareDownloadUrl = $softwareDownloadUrl"
    # 检查是否有 （使用-not运算符判断）
    if ( -not $(which "$softwareName") ){ # 不存在，则下载解压，添加环境变量
        $Url = $softwareDownloadUrl
        # 解析 URL 并获取最后一段路径
        $downloadUrl = [System.Uri]$Url
        $lastSegment = $downloadUrl.Segments[-1]
        # 
        $DownSaveDir = "${env:USERPROFILE}\Downloads\WinSoftwares" # 下载存放位置变量
        # 创建目标目录（如果不存在）
        if (-not (Test-Path -Path $DownSaveDir)) {
            New-Item -Path $DownSaveDir -ItemType Directory -Force | Out-Null
            XWrite-Host "INFO" "A directory has been created: $DownSaveDir" -ForegroundColor Cyan # 已创建目录
        }
        if (-not (Test-Path -Path $EnvDir)) {
            New-Item -Path $EnvDir -ItemType Directory -Force | Out-Null
            XWrite-Host "INFO" "A directory has been created: $EnvDir" -ForegroundColor Cyan # 已创建目录
        }
        # 下载
        Download-Url-File $Url $DownSaveDir
        $DownloadPath = "$DownSaveDir\$lastSegment" # 下载存放位置变量
        XWrite-Host "Debug" "DownloadPath = $DownloadPath"
        if(Test-Path "$EnvPath") {
            # 已存在
        } else {
            # 解压
            $cmd_string="Expand-Archive -Force -LiteralPath $DownloadPath -DestinationPath $DownSaveDir" # 在下载保存目录解
            XWrite-Host "INFO" "cmd_string = $cmd_string"
            Invoke-Expression $cmd_string # 执行命令
            # 移动
            $cmd_string="Move-Item -Path $DownSaveDir\$MoveSubPath -Destination $EnvDir" # 拷贝文件到对应目录下
            XWrite-Host "INFO" "cmd_string = $cmd_string"
            Invoke-Expression $cmd_string # 执行命令
        }
        # 删除下载文件
        if(Test-Path "$DownSaveDir\$MoveSubPath") {
            # $cmd_string= "Remove-Item -Recurse -Force -Path $DownSaveDir\$MoveSubPath\* "
            # XWrite-Host "INFO" "cmd_string = $cmd_string"
            # Invoke-Expression $cmd_string # 执行命令
            $cmd_string= "Remove-Item -Recurse -Force -Path $DownSaveDir\$MoveSubPath" 
            XWrite-Host "INFO" "cmd_string = $cmd_string"
            Invoke-Expression $cmd_string # 执行命令
        }
        # 添加环境变量
        $fullEnvPath = "$EnvPath"
        XWrite-Host "INFO" "fullEnvPath = $fullEnvPath"
        if (Test-Path -Path $fullEnvPath) { # 存在则j
            Check-And-Add-USerEnvVars "$fullEnvPath"
        } else {
            XWrite-Host "Error"  "$fullEnvPath is not exist."
        }
    } else {
        # 存在
        XWrite-Host "Debug"  "$softwareName is exist."
    }

}

# 初始化检查函数6: 下载后需要执行安装的软件
function initMain6($softwareName,$softwareDownloadUrl){
    XWrite-Host "Debug" "initMain6()"
    XWrite-Host "Debug" "softwareName = $softwareName"
    XWrite-Host "Debug" "softwareDownloadUrl = $softwareDownloadUrl"
    # 检查是否有 （使用-not运算符判断）
    if ( -not $(which "$softwareName") ) { # 不存在，则下载解压，添加环境变量
        $Url = $softwareDownloadUrl
        # 解析 URL 并获取最后一段路径
        $downloadUrl = [System.Uri]$Url
        $lastSegment = $downloadUrl.Segments[-1]
        # 
        $DownSaveDir = "${env:USERPROFILE}\Downloads\WinSoftwares" # 下载存放位置变量
        # 创建目标目录（如果不存在）
        if (-not (Test-Path -Path $DownSaveDir)) {
            New-Item -Path $DownSaveDir -ItemType Directory -Force | Out-Null
            XWrite-Host "INFO" "A directory has been created: $DownSaveDir" -ForegroundColor Cyan # 已创建目录
        }
        # 下载
        Download-Url-File $Url $DownSaveDir
        $DownloadPath = "$DownSaveDir\$lastSegment" # 下载存放位置变量
        XWrite-Host "Debug" "DownloadPath = $DownloadPath"
        # 执行静默安装
        installSoftware $DownloadPath   
        # 删除下载文件
    } else {
        # 存在
        XWrite-Host "Debug"  "$softwareName is exist."
    }
}
# ... (保留所有原有的initMain函数)

# 检查并创建写入配置文件
function Check-And-CreateWrite-Config($config_file_path,$config_txt){
    # $config_file_path = "C:\Tools\bin\BBDown.config"
    #echo "[debug] file_path = $file_path"
    # 判断是否下载完成存在文件，存在则进行解压
    $TRUE_FALSE=(Test-Path $config_file_path)
    if($TRUE_FALSE -eq "True") { 
        # 文件存在
        # echo "[debug] BBDown_config_file_path It is exits."
    } else {
        # 文件不存在
        #echo "[debug] BBDown_config_file_path It is not exits."
        # echo "--work-dir $HOME/Downloads `n --skip-ai False " > "C:\Tools\bin\BBDown.config"
        echo "$config_txt" > "$config_file_path"
    }
}

# 解析用户输入（支持范围如8-10）
function Parse-UserSelection {
    param($inputString)
    $selectedIndices = @()
    $parts = $inputString -split ','
    
    foreach ($part in $parts) {
        $part = $part.Trim()
        
        # 处理范围格式 (如 8-10)
        if ($part -match '^(\d+)-(\d+)$') {
            $start = [int]$matches[1]
            $end = [int]$matches[2]
            
            if ($start -le $end) {
                $selectedIndices += $start..$end | ForEach-Object { $_ - 1 }
                # $selectedIndices += $start..$end | ForEach-Object { $_  }
            } else {
                XWrite-Host "WARNING" "Invalid range: $part (start > end)"
            }
        }
        # 处理排除模式 (如 !7)
        elseif ($part -match '^!(\d+)$') {
            # 排除模式在外部处理
            $selectedIndices += $part
        }
        # 处理单个数字
        elseif ($part -match '^\d+$') {
            $selectedIndices += [int]$part - 1
            # $selectedIndices += [int]$part
        }
        # 处理特殊命令 (A/Q)
        else {
            $selectedIndices += $part
        }
    }
    
    return $selectedIndices
}

# 软件定义表
# $softwareList = @(
#     @{
#         Name = "PSTools"
#         Description = "psexec"
#         Install = {
#             # initMain3 "psexec.exe" "C:\Tools" `
#             #     "https://download.sysinternals.com/files/PSTools.zip" "PSTools"
#             # 下载
#             $PSToolsEnv =  'C:\Tools\PSTools'
#             $downloadUrl = "https://download.sysinternals.com/files/PSTools.zip"
#             Download-Url-File $downloadUrl $OutputSavePath
#             # 解压
#             $cmd_string="Expand-Archive -Force -LiteralPath '$OutputSavePath\PSTools.zip' -DestinationPath $PSToolsEnv" # 在下载保存目录解
#             XWrite-Host "INFO" "cmd_string = $cmd_string"
#             Invoke-Expression $cmd_string # 执行命令
#             # 添加环境变量
#             Add-EnvVars "Path" "${PSToolsEnv}\" "User"
#         }
#         Check = { which "psexec.exe" }
#     }
# )

# # 判断是否存在文件
# $databases_file_path="$PSScriptRoot\databases.ps1"
# # echo "[Info] databases_file_path = $databases_file_path" 
# $TRUE_FALSE=(Test-Path $databases_file_path)
# if($TRUE_FALSE -eq "True")
# {
#     # 文件已经存在
#     # echo "[Info] $databases_file_path" 
#     . "$PSScriptRoot\databases.ps1"
# } else {
# 	. "$PSScriptRoot\databases-example.ps1"
# }
. "$PSScriptRoot\databases-init.ps1"


# 懒加载主函数
function LazyLoad-Main {
    XWrite-Host "Debug" "DiySoftware = $DiySoftware"
    # 检查已安装的软件
    $installed = @()
    $notInstalled = @()

    # 如果有指定软件参数，则只处理指定的软件
    $filteredList = if ($DiySoftware) {
        $selectedNames = $DiySoftware -split ',' | ForEach-Object { $_.Trim() }
        
        # 快速查找匹配的软件
        $matchedSoftware = @()
        $invalidNames = @()
        
        foreach ($name in $selectedNames) {
            $found = $softwareList | Where-Object { $_.Name -eq $name }
            if ($found) {
                $matchedSoftware += $found
            } else {
                $invalidNames += $name
            }
        }
        
        if ($invalidNames) {
            XWrite-Host "WARNING" "The following software names are not recognized and will be ignored: $($invalidNames -join ', ')"
            XWrite-Host "INFO" "Available software names: $($softwareList.Name -join ', ')"
        }
        $matchedSoftware
    } else {
        $softwareList
    }
    
    if ( -not [string]::IsNullOrEmpty($DiySoftware)) {  # 如果有输入指定安装软件名
        if ($Software -and -not $filteredList) { # 如果没有匹配的软件
            XWrite-Host "ERROR" "No valid software specified. Available options: $($softwareList.Name -join ', ')"
            return
        } else {
            # # 如果指定了软件参数，直接安装而不显示菜单
            # 执行筛选出来得原有安装
            foreach ($software in $filteredList) {
                $checkResult = & $software.Check
                if ($checkResult) {
                    $installed += $software.Name
                } else {
                    $notInstalled += $software
                }
            }
            foreach ($software in $notInstalled) {
                # XWrite-Host "INFO" "正在安装指定软件: $($software.Name)"
                XWrite-Host "INFO" "Installing specified software: $($software.Name)"
                try {
                    & $software.Install
                    XWrite-Host "SUCCESS" "The installation was successful: $($software.Name)"
                } catch {
                    # XWrite-Host "ERROR" "安装失败: $($software.Name) - $($_.Exception.Message)"
                    XWrite-Host "ERROR" "Installation failed: $($software.Name) - $($_.Exception.Message)"
                }
            }
            return
        }
    }

    # 原有安装
    foreach ($software in $softwareList) {
        $checkResult = & $software.Check
        if ($checkResult) {
            # $installed += $software.Name
            $installed += $software
        } else {
            $notInstalled += $software
        }
    }



    # 显示已安装软件
    if ($installed) {
        # XWrite-Host "INFO" "已安装的软件:"
        XWrite-Host "DEBUG" "Installed software:"
        # $installed | ForEach-Object { XWrite-Host "DEBUG" "  - $_" }
        $installed | ForEach-Object { XWrite-Host "DEBUG" " $($_.Name)  - $($_.Description)" }
        Write-Host ""
    }
    
    # 如果没有需要安装的软件
    if (-not $notInstalled) {
        # XWrite-Host "INFO" "所有推荐软件均已安装!"
        XWrite-Host "DEBUG" "All recommended software is installed!"
        return
    }
    
    # 显示可安装软件
    # XWrite-Host "INFO" "可安装的软件:"
    XWrite-Host "INFO" "Installable software:"
    for ($i = 0; $i -lt $notInstalled.Count; $i++) {
        $software = $notInstalled[$i]
        Write-Host "$($i+1). $($software.Name) - $($software.Description)"
    }


    # 自动安装模式
    if ($All) {
        # XWrite-Host "INFO" "自动安装所有软件..."
        XWrite-Host "INFO" "Automatically installs all software..."
        foreach ($software in $notInstalled) {
            # XWrite-Host "INFO" "正在安装: $($software.Name)"
            XWrite-Host "INFO" "Installing: $($software.Name)"
            try {
                & $software.Install
                # XWrite-Host "SUCCESS" "安装成功: $($software.Name)"
                XWrite-Host "SUCCESS" "The installation was successful\: $($software.Name)"
            } catch {
                # XWrite-Host "ERROR" "安装失败: $($software.Name) - $($_.Exception.Message)"
                XWrite-Host "ERROR" "Installation failed: $($software.Name) - $($_.Exception.Message)"
            }
        }
        return
    }
    
    # 交互式安装
    # $choices = Read-Host "`n请选择要安装的软件编号 (多个用逗号分隔, A=全部, Q=退出)"
    # $choices = Read-Host "`nPlease select the software number to be installed (multiple separated by commas, A=All, Q=Exit)"
    # XWrite-Host "DEBUG" "choices: $choices"
    Write-Host -NoNewline "`nPlease select the software number to be installed (multiple separated by commas, A=All, Q=Exit): "
    $choices = [System.Console]::ReadLine() # 使用 .NET 的 [System.Console]::ReadLine() 完全绕过 PSReadLine
    XWrite-Host "INFO" "choices: $choices"
    if ($choices.StartsWith("!")) {# 处理排除模式（以!开头）
        # 提取排除的编号（转换为0-based索引）
        $excludedIndices = $choices.TrimStart('!') -split "," | ForEach-Object {
            try { [int]$_.Trim() - 1 } catch { -1 }
        }
        XWrite-Host "DEBUG" "excludedIndices: $excludedIndices"
        # 安装所有未安装的软件（排除指定编号）
        for ($i = 0; $i -lt $notInstalled.Count; $i++) {
            if ($excludedIndices -notcontains $i) {
                $software = $notInstalled[$i]
                XWrite-Host "INFO" "Installing:$($i+1) $($software.Name)"
                try {
                    & $software.Install
                    XWrite-Host "SUCCESS" "The installation was successful: $($software.Name)"
                } catch {
                    XWrite-Host "ERROR" "Installation failed: $($software.Name) - $($_.Exception.Message)"
                }
            }
        }
    }
    elseif ($choices -eq "A") { # 安装全部
    # if ($choices -eq "A") {
        # 安装全部
        foreach ($software in $notInstalled) {
            # XWrite-Host "INFO" "正在安装: $($software.Name)"
            XWrite-Host "INFO" "Installing: $($software.Name)"
            try {
                & $software.Install
                XWrite-Host "SUCCESS" "The installation was successful: $($software.Name)"
            } catch {
                # XWrite-Host "ERROR" "安装失败: $($software.Name) - $($_.Exception.Message)"
                XWrite-Host "ERROR" "Installation failed: $($software.Name) - $($_.Exception.Message)"
            }
        }
    }
    elseif ($choices -eq "Q") {
        # XWrite-Host "INFO" "退出安装"
        XWrite-Host "INFO" "Exit the installation"
        exit
    }
    else {
        # 安装选定软件
        # $selectedIndices = $choices -split "," | ForEach-Object { [int]$_ - 1 }
        # XWrite-Host "INFO" "choices: $choices"
        $selectedIndices = Parse-UserSelection $choices # 处理常规选择（包含范围 如 1-8）
        XWrite-Host "DEBUG" "selectedIndices: $selectedIndices"
        foreach ($index in $selectedIndices) {
            if ($index -ge 0 -and $index -lt $notInstalled.Count) {
                $software = $notInstalled[$index]
                # XWrite-Host "INFO" "正在安装: $($software.Name)"
                XWrite-Host "INFO" "Installing:$($index+1). $($software.Name)"
                XWrite-Host "DEBUG" "Install CMD: $($software.Install)"
                try {
                    & $software.Install
                    # XWrite-Host "SUCCESS" "安装成功: $($software.Name)"
                    XWrite-Host "SUCCESS" "The installation was successful: $($software.Name)"
                } catch {
                    # XWrite-Host "ERROR" "安装失败: $($software.Name) - $($_.Exception.Message)"
                    XWrite-Host "ERROR" "Installation failed: $($software.Name) - $($_.Exception.Message)"
                }
            }
            else {
                # XWrite-Host "WARNING" "无效的编号: $($index+1)"
                XWrite-Host "WARNING" "Invalid number: $($index+1)"
            }
        }
    }
}

# 主执行流程
# $githubProxyUrl = "https://github.moeyy.xyz/" # 代理的网址
$githubProxyUrl = "" # 代理的网址
$stopwatch = [System.Diagnostics.Stopwatch]::StartNew() # 开始时间计时

if ($Test) {
    # XWrite-Host "INFO" "测试模式激活"
    XWrite-Host "INFO" "Test mode activation"
    LazyLoad-Main # 开始执行懒加载函数
    # 在测试模式下可以执行额外的调试操作
} else {
    # XWrite-Host "INFO" "Start ..."
    LazyLoad-Main # 开始执行懒加载函数
}

# 检查是否关闭recall
$stopwatch.Stop()
# XWrite-Host "INFO" "执行时间: $($stopwatch.Elapsed.ToString('hh\:mm\:ss\.fff'))"
XWrite-Host "DEBUG" "Execution time: $($stopwatch.Elapsed.ToString('hh\:mm\:ss\.fff'))"